You have seem how R markdown documents work across our exercises. We are now going to look at how R markdown documents can be used to generate literate code by getting a better understanding of code chunks.
# We are going to start by loading our data and set working directories
# Run this chunk unless you have run Exercise 2.1
# setwd("./02_session")
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.4 ✔ readr 2.1.5
## ✔ forcats 1.0.0 ✔ stringr 1.5.1
## ✔ ggplot2 3.5.0 ✔ tibble 3.2.1
## ✔ lubridate 1.9.3 ✔ tidyr 1.3.1
## ✔ purrr 1.0.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
tt_data <- read.csv("./data/tiktok_data.csv")
You can insert an image in your document this way: alt text in [] / image path in () / width and height in {}
You know chunks already. They are the bits prefaced by “```{r}”, whic specifies that a piece of text has to be interpreted as code. Now we can look at a few common options for chunks. Code chunks are the building blocks of R Markdown documents.
Other options for chunks can be access through the chunk options menu.
For instance. Ask to “not run” the last chunk of this document by
checking the chunk options (cogwheel).
If you don’t do that the code won’t compile, because it contains erroneous code (blanks to fill).
At the same time that you go through the output options, I’d like you
to observe the changes in the line introducing the chunk
```{r}. Based on this what is the meaning of
include and echo?
Change the chunk on top of this document so it doesn’t
echo.
You can also run code inline with the text. If I type ’r 5*5’ but with a grave accent (“`”), it will be interpreted as r-code and shown as 25 in the Knitted document (see below).
Finally you want to knit your document. You can do so with the knit button. Explore the options.
We can spice things up by animating your data. Fill the blanks in this chunk.
Insert the gif in this document using the method we saw above.
Key Takeaways
Code Chunks: Use code chunks to run R code and display results in your report. Inline Code: Incorporate R code directly into your text for dynamic reporting. Visualizations: Enhance your reports with plots and charts to illustrate your findings.
Additional Resources
Explore more about R Markdown and its capabilities in the official documentation.